package com.jp.knowledge.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.AttentionData;
import com.jp.knowledge.model.HeadLineData;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.experience.ExperienceModel;
import com.jp.knowledge.util.ResultSubscriber;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

/**
 * Created by 528787067@qq.com on 2017/1/19.
 */

public class SearchCommtemAdapter extends CommtemAdapter {

    private String action;
    private String id;
    private int type;
    private boolean showLabel;
    private DateFormat dateFormat;

    public SearchCommtemAdapter(Context context, List infos) {
        super(context, infos);
        type = -1;
        showLabel = true;
        dateFormat = new SimpleDateFormat("yyyy年MM月", Locale.getDefault());
    }

    public void setAction(String action){
        this.action = action;
    }

    public void setId(String id){
        this.id = id;
    }

    public void setType(int type){
        this.type = type;
    }

    public void setShowLabel(boolean showLabel){
        this.showLabel = showLabel;
    }

    @Override
    protected void renderData(JPRecycleViewHolder holder, Object item, int position) {
        super.renderData(holder, item, position);
        holder.getView(R.id.icon_close).setVisibility(View.GONE);
        HeadLineData headLineData = (HeadLineData) item;
//        if(type != headLineData.getType())
//            return;
        TextView operatingBtn = holder.getView(R.id.operating_btn);
        setOperatingBtn(operatingBtn, headLineData, position);
        if(operatingBtn.getVisibility() == View.VISIBLE){
            holder.getView(R.id.muilt_icon).setVisibility(View.GONE);
            holder.getView(R.id.desc_icon).setVisibility(View.GONE);
        }
        if(headLineData.getType() == 15){   // 文库不显示来源
            holder.getView(R.id.author).setVisibility(View.GONE);
        }
        if(!TextUtils.isEmpty(headLineData.getLabel2())){
            TextView label2 = holder.getView(R.id.navType);
            label2.setVisibility(View.VISIBLE);
            label2.setText(headLineData.getLabel2());
        } else{
            holder.getView(R.id.navType).setVisibility(View.GONE);
        }
        if(!showLabel) {
            holder.getView(R.id.type).setVisibility(View.GONE);
            holder.setText(R.id.time, dateFormat.format(headLineData.getCreatetime()));
        }
        holder.getView(R.id.icon_collection).setVisibility(View.GONE);
    }

    private void setOperatingBtn(TextView operatingBtn, HeadLineData headLineData, int position){
        if(headLineData.getType() == 1 || headLineData.getType() == 16) {   // 头条或团队圈不需要显示右边按钮
            operatingBtn.setVisibility(View.GONE);
            return;
        }
        if("joinExp".equals(action)){
            if(headLineData.getIsExpJoin() == 1) {
                operatingBtn.setText("已加入");
                operatingBtn.setTextColor(mContext.getResources().getColor(R.color.font_gray_think));
                operatingBtn.setBackground(mContext.getResources().getDrawable(R.drawable.search_btn_gray));
            } else {
                operatingBtn.setText("加入");
                operatingBtn.setTextColor(mContext.getResources().getColor(R.color.theme_color));
                operatingBtn.setBackground(mContext.getResources().getDrawable(R.drawable.search_btn_blue));
            }
        } else if("joinRecommend".equals(action) || "joinSubject".equals(action)){
            if(headLineData.getIsJoin() == 1) {
                operatingBtn.setText("已加入");
                operatingBtn.setTextColor(mContext.getResources().getColor(R.color.font_gray_think));
                operatingBtn.setBackground(mContext.getResources().getDrawable(R.drawable.search_btn_gray));
            } else {
                operatingBtn.setText("加入");
                operatingBtn.setTextColor(mContext.getResources().getColor(R.color.theme_color));
                operatingBtn.setBackground(mContext.getResources().getDrawable(R.drawable.search_btn_blue));
            }
        } else {
            switch (headLineData.getType()) {
                case 3:
                case 4:
                case 8:
                case 9:
                    if (headLineData.getIsSubscribe() == 1) {
                        operatingBtn.setText("已监控");
                        operatingBtn.setTextColor(mContext.getResources().getColor(R.color.font_gray_think));
                        operatingBtn.setBackground(mContext.getResources().getDrawable(R.drawable.search_btn_gray));
                    } else {
                        operatingBtn.setText("监控");
                        operatingBtn.setTextColor(mContext.getResources().getColor(R.color.theme_color));
                        operatingBtn.setBackground(mContext.getResources().getDrawable(R.drawable.search_btn_blue));
                    }
                    break;
                case 11:
                case 14:
                case 15:    // 收藏
                    if (headLineData.getIsFollow() == 1) {
                        operatingBtn.setText("已收藏");
                        operatingBtn.setTextColor(mContext.getResources().getColor(R.color.font_gray_think));
                        operatingBtn.setBackground(mContext.getResources().getDrawable(R.drawable.search_btn_gray));
                    } else {
                        operatingBtn.setText("收藏");
                        operatingBtn.setTextColor(mContext.getResources().getColor(R.color.theme_color));
                        operatingBtn.setBackground(mContext.getResources().getDrawable(R.drawable.search_btn_blue));
                    }
                    break;
                default:
                    operatingBtn.setVisibility(View.GONE);
                    return;
            }
        }
//        operatingBtn.setVisibility(View.VISIBLE);
        operatingBtn.setVisibility(View.GONE);
        operatingBtn.setTag(position);
        operatingBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if(view.getId() != R.id.operating_btn) {
            super.onClick(view);
            return;
        }
        int position = (int) view.getTag();
        HeadLineData data = (HeadLineData) getData().get(position);

        JsonObject param = new JsonObject();
        param.addProperty("token", HttpHelper.token);
        param.addProperty("id", data.getId());
        param.addProperty("type", data.getType());
        param.addProperty("subjectId", id);
        if ("joinExp".equals(action)){
            if(data.getIsExpJoin() == 1) {
//                JsonArray jsonArray = new JsonArray();
//                jsonArray.add(data.getId());
//                param.add("ids", jsonArray);
//                HttpHelper.getInstance(context).expMyDelete(param, position * 10 + JOIN_EXP_CODE, httpListener);
                ToasUtil.toast(mContext, "抱歉，不能添加重复产品");
                return;
            } else {
                HttpHelper.getInstance(mContext).joinExp(param, position * 10 + JOIN_EXP_CODE, httpListener);
            }
            data.setIsExpJoin(data.getIsExpJoin()==1 ? 0 : 1);
        } else if("joinRecommend".equals(action)){
            if(data.getIsJoin() == 1)
                HttpHelper.getInstance(mContext).unJoinRecommend(param, position * 10 + JOIN_RECOMMEND_CODE, httpListener);
            else
                HttpHelper.getInstance(mContext).joinRecommend(param, position * 10 + JOIN_RECOMMEND_CODE, httpListener);
            data.setIsJoin(data.getIsJoin()==1 ? 0 : 1);
        } else if("joinSubject".equals(action)){
            HttpHelper.getInstance(mContext).joinSubject(param, position * 10 + JOIN_SUBJECT_CODE, httpListener);
            data.setIsJoin(data.getIsJoin()==1 ? 0 : 1);
        } else {
            switch (data.getType()) {
                case 1:     // 头条
                    break;
                case 3:     // 公司
                case 4:     // 人物
                case 8:     // 产品
                case 9:     // 主题 -----> 关注
                    HttpHelper.getInstance(mContext).subscribeOperate(param, position*10+ATTENTION_CODE, httpListener);
                    data.setIsSubscribe(data.getIsSubscribe()==1 ? 0 : 1);
                    break;
                case 11:    // 全民推荐
                case 14:    // 报告
                case 15:    // 界面 -----> 收藏
                    if(data.getIsFollow() == 1)
                        HttpHelper.getInstance(mContext)
                                .unCollection(param, position*10+COLLECTION_CODE, httpListener);
                    else
                        HttpHelper.getInstance(mContext)
                                .collectionHead(param, position*10+COLLECTION_CODE, httpListener);
                    data.setIsFollow(data.getIsFollow()==1 ? 0 : 1);
                    break;
                case 16:    // 团队圈
                    break;
            }
        }
        notifyItemChanged(position);
    }

    private static final int JOIN_EXP_CODE = 0x01;
    private static final int JOIN_RECOMMEND_CODE = 0x02;
    private static final int JOIN_SUBJECT_CODE = 0x03;
    private static final int ATTENTION_CODE = 0x04;
    private static final int COLLECTION_CODE = 0x05;
    private ResultSubscriber.OnResultListener httpListener = new ResultSubscriber.OnResultListener() {
        @Override
        public void onStart(int requestType) {}
        @Override
        public void onCompleted(int requestType) {}
        @Override
        public void onError(int requestType) {
            ToasUtil.toast(mContext, "抱歉，操作失败");
            HeadLineData headLineData = (HeadLineData) getData().get(requestType/10);
            switch (requestType%10){
                case JOIN_EXP_CODE:
                    headLineData.setIsExpJoin(headLineData.getIsExpJoin()==1 ? 0 : 1);
                    break;
                case JOIN_RECOMMEND_CODE:
                case JOIN_SUBJECT_CODE:     // 加入
                    headLineData.setIsJoin(headLineData.getIsJoin()==1 ? 0 : 1);
                    break;
                case ATTENTION_CODE:
                    headLineData.setIsSubscribe(headLineData.getIsSubscribe()==1 ? 0 : 1);
                    break;
                case COLLECTION_CODE:
                    headLineData.setIsFollow(headLineData.getIsFollow()==1 ? 0 : 1);
                    break;
            }
            notifyItemChanged(requestType/10);
        }
        @Override
        public void onNext(IModel data, int requestType) {
            if(data.getErrcode() != 0) {
                onError(requestType);
            } else if(requestType%10 == JOIN_EXP_CODE) {
                /* 添加体验后发送广播通知体验刷新数据 */
                List<ExperienceModel> joinApps = data.getList(ExperienceModel.class);
                Intent intent = new Intent(LocalBroadCast.ADD_EXP_APP);
                intent.putExtra("appData", (Serializable) joinApps);
                if(joinApps != null && joinApps.size() > 0)
                    intent.putExtra("gid", joinApps.get(0).getGid());
                LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
            } else if(requestType%10 == ATTENTION_CODE){
                /* 发送广播刷新雷达 */
                HeadLineData headLineData = (HeadLineData) getData().get(requestType/10);
                AttentionData attentionData = new AttentionData();
                attentionData.setId(headLineData.getId());
                attentionData.setIcon(headLineData.getIcon());
                attentionData.setType(headLineData.getType());
                attentionData.setTitle(headLineData.getTitle());
                attentionData.setSource(headLineData.getSource());
                attentionData.setNewNum(0);
                attentionData.setCountNum(0);
                attentionData.setAddress(headLineData.getAddress());
                attentionData.setAttentionTime(System.currentTimeMillis());
                attentionData.setSubscribeNum(0);
                Intent intent = new Intent(LocalBroadCast.ADD_ATTENTION);
                intent.putExtra("isAttention", headLineData.getIsSubscribe()==1);
                intent.putExtra("attentionData", attentionData);
                LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
            }
        }
    };
}
